<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Copyright as admin;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Config;

class CopyrightService
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $model = admin::whereNotNull('name')->find();
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 保存数据
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(array $data)
    {
        $model = admin::whereNotNull('name')->find();
        if (empty($model->token)) {
            return [HTTP_NOTACCEPT, '版权未激活，请先激活'];
        }
        if (!$model) {
            $model = admin::create($data);
        } else {
            $model->save($data);
        }
        return [HTTP_CREATED, $model];
    }

    //版权远程授权
    public function active()
    {

        $model = admin::whereNotNull('name')->find();
        if(!empty($model->token)){
            return [HTTP_SUCCESS, $model->token];
        }
        $base = Config::get("base.zongkong_domain", "https://ddu.jingzhe365.com");

        $url = "{$base}/authentication/check/copyright";
        $license = request()->post('license', '');
        $uniqid="JC".uniqid();
        $body = [
            ['name' => 'license', 'contents' => $license,'uniqid'=>$uniqid]
        ];
        $authentication = new AuthenticationService();
        try {
            $response = $authentication->request("post", $url, $body);
        } catch (GuzzleException $e) {
            return [HTTP_NOTACCEPT, "插件鉴权失败" . $e->getMessage()];
        }
        $token = $response['msg'];

        if (!$model) {
            $data = [
                'name' => '节程商城系统开源版 ',
                'mobile' => '',
                'logo' => 'https://q.jc362.com/storage/favicon.png?1637204530',
                'record_number' => '浙ICP备18011642号',
                'token' => '',
                'url'=>'',
            ];
            $model = admin::create($data);
        }
        $model->uniqid = $uniqid;
        $model->token = $token;
        $model->save();
        return [HTTP_SUCCESS, $token];
    }
}
